<template>
  <div style="width: 1200px; margin: auto">
    <h3 style="text-align: left">基础信息</h3>
    <br />
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
      style="max-width: 1300px; width: 1100px; margin: auto"
    >
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="产品编号" prop="product_Code">
            <el-input
              v-model="form.product_Code"
              style="width: 355px"
              :disabled="type.length > 0"
              clearable
            />
            <!-- <el-checkbox-group v-model="form.type"> -->

            <!-- </el-checkbox-group> -->
          </el-form-item>

          <el-form-item label="规格型号" prop="model_Number">
            <el-input v-model="form.model_Number" />
          </el-form-item>
          <el-form-item label="单位" prop="unit_Id">
            <el-select
              v-model="form.unit_Id"
              placeholder="请选择单位"
              clearable
            >
              <el-option
                v-for="item in productUnitInfoList"
                :key="item.UnitId"
                :label="item.UnitName"
                :value="item.UnitId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品属性" prop="product_Attributes_Id">
            <el-select
              v-model="form.product_Attributes_Id"
              placeholder="请选择产品属性"
              clearable
            >
              <el-option
                v-for="item in productList"
                :key="item.AttId"
                :label="item.AttName"
                :value="item.AttId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="最小库存数" prop="minimum_Stock_Quantity">
            <el-input v-model="form.minimum_Stock_Quantity" />
          </el-form-item>
          <el-form-item label="产品有效期" prop="product_Expiry_Date">
            <el-input
              v-model="form.product_Expiry_Date"
              style="width: 360px"
            />&nbsp;&nbsp;&nbsp;&nbsp;天 &nbsp;&nbsp;&nbsp;&nbsp;
            <el-checkbox value="Online activities" name="type">无</el-checkbox>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :value="true">启用</el-radio>
              <el-radio :value="false">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="产品名称" prop="product_Name">
            <el-input v-model="form.product_Name" />
          </el-form-item>
          <el-form-item label="品牌" prop="brand">
            <el-input v-model="form.brand" />
          </el-form-item>
          <el-form-item label="产品分类" prop="product_Category_Id">
            <el-select
              v-model="form.product_Category_Id"
              placeholder="请选择产品分类"
              clearable
            >
              <el-option
                v-for="item in productinfoList"
                :key="item.TypeId"
                :label="item.TypeName"
                :value="item.TypeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="销售单价" prop="unit_Price">
            <el-input v-model="form.unit_Price" />
          </el-form-item>
          <el-form-item label="最大库存数" prop="maximum_Stock_Quantity">
            <el-input v-model="form.maximum_Stock_Quantity" />
          </el-form-item>
          <el-form-item label="报警天数" prop="alert_Days">
            <el-input
              v-model="form.alert_Days"
              style="width: 410px"
            />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;天
          </el-form-item>
        </el-col></el-row
      >
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="form.remarks" type="textarea" />
      </el-form-item>
      <el-form-item label="图片">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:5055/api/Product/UpFile"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-change="handleSuccess"
        >
          <img
            v-if="form.product_Image"
            :src="'http://localhost:5055/PIC/' + form.product_Image"
            class="avatar"
            style="width: 200px; height: 200px; object-fit: cover"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <p style="margin: auto">
          <el-button type="primary" @click="editProduct(ruleFormRef)">
            修改
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </p>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElUpload } from "element-plus";
import axios from "axios";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { useRouter, useRoute } from "vue-router";

const route = useRoute();
const router = useRouter();

const productList = ref([]);
const productinfoList = ref([]);
const productUnitInfoList = ref([]);
const type = ref([]);

// do not use same name with ref
interface RuleForm {
  product_Id: string;
  product_Code: string;
  product_Name: string;
  model_Number: string;
  brand: string;
  unit_Id: string;
  product_Category_Id: string;
  product_Attributes_Id: string;
  unit_Price: string;
  minimum_Stock_Quantity: string;
  maximum_Stock_Quantity: string;
  product_Expiry_Date: string;
  alert_Days: string;
  status: string;
  remarks: string;
  product_Image: string;
}
//const checkList = ref([]);
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const form = reactive<RuleForm>({
  product_Id: "",
  product_Code: "",
  product_Name: "",
  model_Number: "",
  brand: "",
  unit_Id: "",
  product_Category_Id: "",
  product_Attributes_Id: "",
  unit_Price: "",
  minimum_Stock_Quantity: "",
  maximum_Stock_Quantity: "",
  product_Expiry_Date: "",
  alert_Days: "",
  status: "",
  remarks: "",
  product_Image: "",
});

const GetProductUnitInfoSel = () => {
  axios
    .get(`Product/GetStockInSel?product_Id=` + route.query.product_Id)
    .then((res) => {
      if (res.data.Code == 200) {
        if (res.data.Data.Product_Code) {
          type.value = ["System Number"]; // 设置 type 数组为非空值，使产品编号禁用
        } else {
          type.value = []; // 设置 type 数组为空值，使产品编号启用
        }
        form.product_Id = res.data.Data.Product_Id;
        form.product_Code = res.data.Data.Product_Code;
        form.product_Name = res.data.Data.Product_Name;
        form.model_Number = res.data.Data.Model_Number;
        form.brand = res.data.Data.Brand;
        form.unit_Id = res.data.Data.Unit_Id;
        form.product_Category_Id = res.data.Data.Product_Category_Id;
        form.product_Attributes_Id = res.data.Data.Product_Attributes_Id;
        form.unit_Price = res.data.Data.Unit_Price;
        form.minimum_Stock_Quantity = res.data.Data.Minimum_Stock_Quantity;
        form.maximum_Stock_Quantity = res.data.Data.Maximum_Stock_Quantity;
        form.product_Expiry_Date = res.data.Data.Product_Expiry_Date;
        form.alert_Days = res.data.Data.Alert_Days;
        form.status = res.data.Data.Status;
        form.remarks = res.data.Data.Remarks;
        form.product_Image = res.data.Data.Product_Image;
      }
    });
};
const editProduct = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      axios.put("Product/UpdateProductSel", form).then((res) => {
        if (res.data.Code == 200) {
          ElMessage.success(res.data.Message);
          router.push("/UserList/productList");
        } else {
          ElMessage.error("修改失败！");
        }
      });
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const rules = reactive<FormRules<RuleForm>>({
  product_Code: [
    { required: true, message: "请输入产品编号", trigger: "blur" },
    { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
  ],
  model_Number: [
    {
      required: true,
      message: "请输入规格型号",
      trigger: "change",
    },
  ],
  product_Name: [
    {
      required: true,
      message: "请输入产品名称",
      trigger: "change",
    },
  ],
  brand: [
    {
      required: true,
      message: "请输入品牌",
      trigger: "change",
    },
  ],
  unit_Id: [
    {
      required: true,
      message: "请输入单位",
      trigger: "change",
    },
  ],
  product_Category_Id: [
    {
      required: true,
      message: "请输入产品分类",
      trigger: "change",
    },
  ],
  product_Attributes_Id: [
    {
      required: true,
      message: "请输入产品属性",
      trigger: "change",
    },
  ],
  unit_Price: [{ required: true, message: "请输入销售单价", trigger: "blur" }],
  minimum_Stock_Quantity: [
    { required: true, message: "请输入最小库存数", trigger: "blur" },
  ],
  maximum_Stock_Quantity: [
    { required: true, message: "请输入最大库存数", trigger: "blur" },
  ],
  product_Expiry_Date: [
    { required: true, message: "请输入产品有效期", trigger: "blur" },
  ],
  alert_Days: [{ required: true, message: "请输入报警天数", trigger: "blur" }],
  remarks: [{ required: true, message: "请输入备注", trigger: "blur" }],
  product_Image: [
    { required: true, message: "请输入产品图片", trigger: "blur" },
  ],
});

// const beforeAvatarUpload = (file) => {
//   const isJPG = file.type === "image/jpeg";
//   const isLt200KB = file.size / 1024 / 1024 < 2;

//   if (!isJPG) {
//     ElMessage.error("上传头像图片只能是 JPG 格式!");
//   }
//   if (!isLt200KB) {
//     ElMessage.error("上传头像图片大小不能超过 2MB!");
//   }
//   return isJPG && isLt200KB;
// };

const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  form.product_Image = response;
};

const handleSuccess = (file) => {
  let fd = new FormData();
  fd.append("file", file.raw);
  form.product_Image = form.product_Image;
};

const GetProductUnitInfoList = () => {
  axios.get("Product/GetProductUnitInfoShow").then((res) => {
    productUnitInfoList.value = res.data;
  });
};

const GetProductinfoList = () => {
  axios.get("Product/GetProductinfoShow").then((res) => {
    productinfoList.value = res.data;
  });
};

const GeProductList = () => {
  axios.get("Product/GetProductShow").then((res) => {
    productList.value = res.data;
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

GetProductUnitInfoSel();
GetProductUnitInfoList();
GeProductList();
GetProductinfoList();
</script>
<style >
.avatar-uploader .el-upload {
  border: 2px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  border-color: white;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.form-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-title {
  text-align: left;
  color: #333;
  font-size: 24px;
  margin-bottom: 20px;
}

.input-large {
  width: 90%;
}

.el-button {
  margin-right: 10px;
  font-size: 16px;
  border-radius: 20px;
}

.el-button[type="primary"] {
  background-color: #409eff;
  color: #fff;
}

.el-button[type="primary"]:hover {
  background-color: #66b1ff;
}

.el-button[plain] {
  color: #409eff;
}
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.form-wrapper {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.form {
  max-width: 100%;
}

.button-group {
  text-align: center;
  margin-top: 20px;
}

.button-group .el-button {
  margin: 0 10px;
  border-radius: 20px;
  padding: 10px 20px;
}
</style>
